package com.zhangbo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhangbo.entity.User;
import com.zhangbo.service.ArticleService;
import com.zhangbo.service.UserService;
import com.zhangbo.utils.CmsContant;

@Controller
@RequestMapping("user")
public class UserController {

	@Value("${upload.path}")
	String uploadPath;

	@Autowired
	UserService usera;
	
	@Autowired
	ArticleService articleService;

//	@Autowired
//	Arti

	// 注册页面
	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register(HttpServletRequest request) {
		request.setAttribute("user", new User());
		return "register";
	}

	// 注册页面发来的请求
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public String register(HttpServletRequest request,
			@Valid @ModelAttribute("user") User user,
			BindingResult result) {
		
		if (result.hasErrors()) {
			return "register";
		}
		if (user.getUname().contains("3")) {
			result.rejectValue("uname", "", "用户名不能包含数字3");
		}
		if (result.hasErrors()) {
			return "register";
		}
		int reigsterResult = usera.register(user);
		if (reigsterResult > 0) {
			return "redirect:login";
		}
		request.setAttribute("error", "注册失败");
		return "register";
	}

	// 登录页面
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request) {
		request.setAttribute("user", new User());
		return "Login";
	}

	// 接收登录页面传输的数据
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,User user) {
		
		User loginUser = usera.login(user);
		if(loginUser!=null) {
			// 千万不要用hard code 硬编码
			request.getSession().setAttribute(CmsContant.USER_KEY, loginUser);
			return loginUser.getRole() ==CmsContant.ROLE_ADMIN ? "redirect:/admin/index" :  "redirect:/user/home";
		}
		
		return "login";
	}
	@RequestMapping("checkuser")
	@ResponseBody
	public boolean checkuser(String uname) {
		User user = usera.findByName(uname);
		return (user == null);
	}

	@RequestMapping("home")
	public String home(HttpServletRequest request) {
		return "home/index";
	}
	
	@RequestMapping("addArticle")
	public String addArticle(HttpServletRequest request) {
		//articleService.list(page)
		return "";
	}

}
